#include "RingQueue.hpp"
#include <ctime>
#include <cstdlib>
#include <unistd.h>
#include "Task.hpp"

class ThreadData
{
public:
    ThreadData(RingQueue<Task> *rq, const std::string &name)
        : _rq(rq), _name(name)
    {
    }
    RingQueue<Task> *_rq;
    std::string _name;
};

void *Consumer(void *args)
{
    RingQueue<Task> *rq = static_cast<RingQueue<Task> *>(args);
    while (true)
    {
        Task t;
        rq->Pop(&t);
        t();
        std::cout << "consumer data: " << t.PrintResult() << std::endl;
        // sleep(1);
    }
    return nullptr;
}

void *Productor(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    while (true)
    {
        int data1 = rand() % 10;
        usleep(rand() % 123);
        int data2 = rand() % 10;
        usleep(rand() % 123);
        char oper = opers[rand() % (opers.size())];
        Task t(data1, data2, oper);
        std::cout << "productor task: " << t.PrintTask() << std::endl;
        td->_rq->Push(t);
        // sleep(1);
    }
    return nullptr;
}

int main()
{
    srand((int16_t)time(nullptr) ^ getpid() ^ pthread_self());
    RingQueue<Task> *rq = new RingQueue<Task>;
    pthread_t p[3], c[2];
    ThreadData *td1 = new ThreadData(rq, "Proc-1");
    pthread_create(&p[0], nullptr, Productor, (void *)td1);

    ThreadData *td2 = new ThreadData(rq, "Proc-2");
    pthread_create(&p[1], nullptr, Productor, (void *)td2);

    ThreadData *td3 = new ThreadData(rq, "Proc-3");
    pthread_create(&p[2], nullptr, Productor, (void *)td3);

    pthread_create(&c[0], nullptr, Consumer, (void *)rq);
    pthread_create(&c[1], nullptr, Consumer, (void *)rq);

    pthread_join(p[0], nullptr);
    pthread_join(p[1], nullptr);
    pthread_join(p[2], nullptr);
    pthread_join(c[0], nullptr);
    pthread_join(c[1], nullptr);
    delete rq;
    delete td1;
    delete td2;
    delete td3;
    return 0;
}